package com.lhl.jwt.handler;


import com.lhl.jwt.exception.JwtParseException;
import com.lhl.jwt.utils.CacheManager;
import com.lhl.jwt.utils.JwtConstant;
import com.nimbusds.jwt.SignedJWT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

/**
 * 注销登录 将token 加入黑名单
 * @author king
 */
@Slf4j
public class LogoutBlacklistHandler implements LogoutHandler {

	@Override
	public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
		SignedJWT jwt = getJwtToken(request);
		
		CacheManager.setData(jwt.getParsedString(), jwt, extractExpireTime(jwt));
	}

	private int extractExpireTime(SignedJWT jwt) {
		try{
			int expire = 0;
			Date expiresAt = jwt.getJWTClaimsSet().getExpirationTime();
			if (!expiresAt.before(Calendar.getInstance().getTime())) {
				expire = (int) (expiresAt.getTime() - System.currentTimeMillis());
			}
			return expire;
		}catch (ParseException e){
			throw new JwtParseException(JwtConstant.TOKEN_NOT_EMPTY);
		}

	}
	
	private SignedJWT getJwtToken(HttpServletRequest request) {
		String authInfo = request.getHeader(JwtConstant.AUTHORIZATION_HEADER);
		if (StringUtils.isBlank(authInfo)) {
			throw new BadCredentialsException(JwtConstant.TOKEN_NOT_EMPTY);
		}
		try {
		    return SignedJWT.parse(StringUtils.removeStart(authInfo, JwtConstant.AUTHORIZATION_START_STRING));
		}catch (ParseException e){
			throw new JwtParseException(JwtConstant.TOKEN_NOT_EMPTY);
		}
	}

}
